<template>
  <je-modal
    v-model:visible="visible"
    class="number-designer"
    width="1200px"
    :title="title"
    height="auto"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <div style="width: 100%; height: 100%; overflow: hidden">
      <je-table
        ref="xNumberTable"
        show-overflow
        keep-source
        height="400"
        auto-resize
        draggable
        sync-resize
        :scroll-y="{ mode: 'wheel' }"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showUpdateStatus: true,
          activeMethod: isTableEdit,
        }"
        :store="tableData"
        :cell-class-name="cellClassName"
        :edit-rules="validRules"
        size="mini"
        align="center"
        @drop="numberDesignerDrop"
      >
        <je-table-column field="index" title="序号" width="50" align="center" :edit-render="{}">
          <template #edit="{ row }">
            {{ row.index }}
          </template>
        </je-table-column>
        <je-table-column field="qzfs" title="取值方式" :edit-render="{}" width="140" align="center">
          <template #edit="{ row }">
            <je-select
              v-model:value="row.qzfs"
              allow-clear
              config-info="JE_FUNC_SERIAL_TYPE,row.qzfs,code,S"
            />
          </template>
          <template #default="{ row }">{{
            getSelectCodeToLabel('JE_FUNC_SERIAL_TYPE', row.qzfs)
          }}</template>
        </je-table-column>
        <je-table-column field="dyz" title="对应值" :edit-render="{}" width="220" align="center">
          <template #default="{ row }">{{
            row.qzfs == 'CL' ? row.dyz : getValueToLable(row)
          }}</template>
          <template #edit="{ row }">
            <je-select
              v-model:value="row.dyz"
              :editable="row.qzfs == 'CL'"
              allow-clear
              style="text-align: left"
              :options="getValueWay[row.qzfs]"
              :show-search="row.qzfs == 'BDZD'"
              :get-popup-container="getPopupContainer"
            >
              <template #option="{ value, label }">
                <div :aria-label="value"
                  >{{ label }}
                  <div v-if="row.qzfs == 'BDZD'" style="color: #d8d8d8">{{ value }}</div></div
                >
              </template>
            </je-select>
          </template>
        </je-table-column>
        <je-table-column field="gs" title="格式「仅用于日期」" :edit-render="{}" align="center">
          <template #edit="{ row }">
            <je-select
              v-model:value="row.gs"
              allow-clear
              config-info="JE_FUNC_DATAFORMAT,row.gs,code,S"
            />
          </template>
          <template #default="{ row }">{{
            getSelectCodeToLabel('JE_FUNC_DATAFORMAT', row.gs)
          }}</template>
        </je-table-column>
        <je-table-column field="jqws" width="100" :edit-render="{ autofocus: '.ant-input' }">
          <template #header>
            <div>
              <i
                class="fas fa-question-circle"
                style="color: #c0c4cc"
                :style="changeColor(unitTipShow)"
                @click="clickTipView"
                @mouseenter="unitTipShow = true"
                @mouseleave="unitTipShow = false"
              />
              截取位数
            </div>
          </template>
          <template #edit="{ row }">
            <je-input v-model:value="row.jqws" />
          </template>
        </je-table-column>
        <je-table-column
          field="cd"
          title="长度"
          width="100"
          :edit-render="{ autofocus: '.ant-input-number-input' }"
        >
          <template #edit="{ row }">
            <je-input-number v-model:value="row.cd" :min="0"></je-input-number>
          </template>
        </je-table-column>
        <je-table-column
          field="qsh"
          title="起始号"
          width="100"
          :edit-render="{ autofocus: '.ant-input' }"
        >
          <template #edit="{ row }">
            <je-input v-model:value="row.qsh" :min="0"></je-input>
          </template>
        </je-table-column>
        <je-table-column
          field="bc"
          title="步长"
          width="100"
          :edit-render="{ autofocus: '.ant-input-number-input' }"
        >
          <template #edit="{ row }">
            <je-input-number v-model:value="row.bc" :min="0"></je-input-number>
          </template>
        </je-table-column>
        <je-table-column field="zq" title="周期" :edit-render="{}" width="100" align="center">
          <template #edit="{ row }">
            <je-select
              v-model:value="row.zq"
              allow-clear
              config-info="JE_FUNC_SERIAL_CYCLE,row.zq,code,S"
            >
            </je-select>
          </template>
          <template #default="{ row }">{{
            getSelectCodeToLabel('JE_FUNC_SERIAL_CYCLE', row.zq)
          }}</template>
        </je-table-column>
        <je-table-column width="40" align="center">
          <template #header>
            <i
              style="font-size: 16px; cursor: pointer"
              class="fal fa-plus"
              @click="addColumnNumber"
            ></i>
          </template>
          <template #default="{ row }">
            <i
              style="font-size: 16px; cursor: pointer"
              class="fal fa-times"
              @click="deleteColumnNumber(row)"
            ></i>
          </template>
        </je-table-column>
      </je-table>
    </div>
  </je-modal>
</template>

<script>
  import {
    ref,
    toRefs,
    reactive,
    defineComponent,
    onMounted,
    onBeforeMount,
    nextTick,
    watch,
  } from 'vue';
  import { Grid, Modal, InputNumber, Select, Input, Data } from '@jecloud/ui';
  import { GetPluginItemConfig as GetFormFieldConfigData } from '@/api/index';
  import { TRUNCATION_NUMBER_UNITPLE } from '@/helper/tip-constant.jsx';
  import {
    getDDItemCache,
    loadDDItemByCodes,
    getDDItemInfo,
    isNotEmpty,
    getDDItemList,
  } from '@jecloud/utils';

  export default defineComponent({
    name: 'NumberDesigner',
    components: {
      JeModal: Modal,
      JeInputNumber: InputNumber,
      JeSelect: Select,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeInput: Input,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      const validRules = ref({
        qzfs: [{ required: true, message: '该输入项为必填项' }],
      });
      const tabledata = props.recordData.value ? JSON.parse(props.recordData.value) : [];
      const state = reactive({
        unitTipShow: false, // 截取位数说明默认不显示
        visible: props.visble,
        title: '编号设计器',
        activeKey: ['1', '2', '3'],
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        getValueWay: {},
        // 对应之的数据
        xNumberTable: ref(),
        formFieldList: [],
      });

      // 查询参数table增加
      const addColumnNumber = () => {
        const record = {
          qzfs: '',
          dyz: '',
          gs: '',
          jqws: '',
          cd: '',
          qsh: '',
          bc: '',
          zq: '',
          dyzData: [],
          index: state.tableData.data.length + 1,
        };
        state.tableData.insert(record, -1);
      };
      const methods = {
        getDefaultData() {
          // 从数据字典中全局变量的数据，将code变成value,text变成label
          const data = getDDItemCache('JE_DEFAULEVALUE') || [];
          const defaultData = [];
          data.map((item) => {
            defaultData.push({ label: item.text, value: item.code });
          });
          return defaultData;
        },
        getPopupContainer() {
          return document.body;
        },

        // 点击截取位数的文字说明
        clickTipView() {
          Modal.alert({
            content: TRUNCATION_NUMBER_UNITPLE,
            title: '截取位数说明',
            icon: 'fal fa-info-circle',
            status: 'info',
            width: 540,
          });
        },
        // 改变tip浮上去的颜色
        changeColor(flag) {
          if (flag) {
            return 'cursor:pointer;color: #3265F5';
          }
          return 'cursor:pointer;';
        },
        // 禁止点击
        isTableEdit({ row, column }) {
          if (row.qzfs == 'CL' && ['gs', 'jqws', 'cd', 'qsh', 'zq', 'bc'].includes(column.field)) {
            return false;
          } else if (row.qzfs == 'QJBL' && ['bc', 'cd', 'qsh', 'zq'].includes(column.field)) {
            return false;
          } else if (row.qzfs == 'LSH' && ['gs', 'jqws'].includes(column.field)) {
            return false;
          } else if (row.qzfs == 'BDZD' && ['bc', 'cd', 'qsh', 'zq'].includes(column.field)) {
            return false;
          } else {
            return true;
          }
        },
        // 拖拽排序
        numberDesignerDrop() {
          state.tableData.data.forEach((item, index_) => {
            item.index = index_ + 1;
          });
        },
        // 获取表单字段
        getFields() {
          // 1.获取功能ID
          state.formFieldList = [];
          const funcCode = props.recordData.funcCode || '';
          const params = {
            tableCode: 'JE_CORE_RESOURCEFIELD',
            j_query: JSON.stringify({
              custom: [
                { code: 'RESOURCEFIELD_FUNCINFO_ID', value: funcCode, type: '=', cn: 'and' },
                {
                  code: 'RESOURCEFIELD_XTYPE',
                  value: ['fieldset', 'displayfield', 'childfuncfield'],
                  type: 'notIn',
                  cn: 'and',
                },
              ],
              order: [{ code: 'SY_ORDERINDEX', type: 'ASC' }],
            }),
            funcId: funcCode,
          };
          GetFormFieldConfigData(params)
            .then((res) => {
              res.rows.map((item) => {
                state.formFieldList.push({
                  value: item.RESOURCEFIELD_CODE,
                  label: item.RESOURCEFIELD_NAME,
                });
              });
            })
            .catch((error) => {
              console.log(error);
            });
        },
        cellClassName({ row, column }) {
          const flag = methods.isTableEdit({ row, column });
          if (!flag) return 'disableBg';
          return '';
        },
        handleClose() {
          state.visible = false;
          emit('changeModal', { isShow: false, isRefresh: false });
        },

        handleOk() {
          // 点击确定的时候获取表格里面的数据
          // methods.handleReset();
          const $table = state.xNumberTable.$plugin;
          $table.validate(state.tableData.data, (errMap) => {
            if (errMap) {
              console.log('校验不通过');
              return false;
            }

            state.visible = false;
            const data = JSON.parse(JSON.stringify(state.tableData.data));
            data.forEach((item) => {
              delete item.dyzData;
              delete item._X_ROW_KEY;
              delete item.__action__;
              delete item.id;
            });
            emit('changeModal', {
              visble: state.visible,
              key: 'RESOURCEFIELD_CONFIGINFO',
              value: (data.length && JSON.stringify(data)) || '',
              change: 'change',
            });
          });

          return false;
        },

        deleteColumnNumber(record) {
          state.tableData.remove(record);
        },

        getValueToLable(row) {
          if (row.dyz == '') {
            return '';
          }
          const list = state.getValueWay[row.qzfs];
          return list.find((item) => item.value == row.dyz)?.label || '';
        },
        getSelectCodeToLabel(dictionary, code) {
          const item = getDDItemInfo(dictionary, code);

          if (isNotEmpty(item)) {
            return item.text;
          }
          return '';
        },
      };
      watch(
        () => state.formFieldList,
        () => {
          state.getValueWay['BDZD'] = state.formFieldList;
        },
        { deep: true },
      );
      onBeforeMount(() => {
        methods.getFields();
        // 获取字典数据
        loadDDItemByCodes([
          'JE_FUNC_DATAFORMAT',
          'JE_FUNC_SERIAL_TYPE',
          'JE_FUNC_SERIAL_CYCLE',
          'JE_DEFAULEVALUE',
        ]).then(() => {
          // 1.拼装对应值
          (getDDItemList('JE_FUNC_SERIAL_TYPE') || []).map((item_) => {
            const { code } = item_;
            let selectData = [];
            if (code == 'QJBL') {
              selectData = methods.getDefaultData();
            } else if (code == 'BDZD') {
              selectData = state.formFieldList;
            } else if (code == 'LSH') {
              selectData = [
                { label: '功能', value: 'FUNC' },
                { label: '表名', value: 'TABLE' },
              ];
            } else {
              selectData = [];
            }
            state.getValueWay[code] = selectData;
          });
        });
      });
      onMounted(() => {
        nextTick(() => {
          state.tableData.loadData(tabledata);
        });
      });
      return {
        ...toRefs(state),
        ...methods,
        addColumnNumber,
        validRules,
      };
    },
  });
</script>
<style lang="less" scoped>
  .number-designer {
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
        cursor: pointer;
      }
    }
  }
</style>
<style lang="less">
  .number-designer {
    .ant-select {
      width: 100% !important;
    }
    .disableBg {
      background: #f5f5f5 !important;
    }
  }
</style>
